﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace PS.ImageRotator.Code
{
    [ServiceContract]
    public interface IImageRotatorService
    {
        /// <summary>
        /// Get the stories.
        /// </summary>
        /// <returns>Featured Stories Collection.</returns>
        [OperationContract]
        [WebGet(UriTemplate = "GetStories", ResponseFormat = WebMessageFormat.Xml)]
        FeaturedStories GetStories();
    }
    /// <summary>
    /// Web Service.
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class ImageRotatorService : IImageRotatorService
    {
        #region Nested Classes

        /// <summary>
        /// Comparer class.
        /// </summary>
        class StoryComparer : IComparer<FeaturedStory>
        {
            /// <summary>
            /// Compare.
            /// </summary>
            /// <param name="x">X.</param>
            /// <param name="y">Y.</param>
            /// <returns></returns>
            public int Compare(FeaturedStory x, FeaturedStory y)
            {
                return string.Compare(x.DisplayOrder, y.DisplayOrder);
            }
        }

        #endregion Nested Classes

        #region Fields

        private const string DisplayOrderFieldName = "Position";
        private const string ImageFieldName = "Image URL";
        private const string StoryLinkFieldName = "Story URL";
        //private const string SubTitleFieldName = "Image Caption";
        //private const string StoryStartFieldName = "StoryStartDate";
        //private const string ExpirationFieldName = "StoryExpiration";

        #endregion Fields

        #region Methods

        /// <summary>
        /// Get the stories.
        /// </summary>
        /// <returns>Featured Stories Collection.</returns>
        public FeaturedStories GetStories()
        {
            var stories = new FeaturedStories();
            try
            {
                string siteUrl = SPContext.Current.Site.Url;

                SPSecurity.RunWithElevatedPrivileges(() =>
                                                         {
                                                             try
                                                             {
                                                                 using (var site = new SPSite(siteUrl))
                                                                     //using (var site = new SPSite(SPContext.Current.Site.Url))
                                                                     //using (var site = new SPSite("http://psdprom01/sites/pranav"))
                                                                 using (SPWeb web = site.OpenWeb())
                                                                 {

                                                                     SPList list = web.Lists["Image Rotator"];
                                                                     if (list != null) stories = GetItems(list);
                                                                 }
                                                             } catch(Exception ex)
                                                             { SPDiagnosticsService.Local.WriteTrace(2, new SPDiagnosticsCategory("Portal Solutions", TraceSeverity.Unexpected, EventSeverity.ErrorCritical), TraceSeverity.Unexpected, ex.Message + ex.StackTrace); }
                                                         });
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(1, new SPDiagnosticsCategory("Portal Solutions", TraceSeverity.Unexpected, EventSeverity.ErrorCritical), TraceSeverity.Unexpected, ex.Message + ex.StackTrace);
                //Log.Dump(ex, GetType(), "Unable to retrieve featured stories: " + ex.Message);
            }
            return stories;
        }

        /// <summary>
        /// Get the list items.
        /// </summary>
        /// <param name="list">SP list instance.</param>
        /// <returns>Featured Stories.</returns>
        private static FeaturedStories GetItems(SPList list)
        {
            //var caml = new CAMLQuery();

            // Get all regardless of expiration.
            //var root = new CAMLOperatorNode("And");
            //root.ChildNodes.Add(new CAMLValueNode("Geq", "DateTime", ExpirationFieldName, "<Today />"));
            //root.ChildNodes.Add(new CAMLValueNode("Leq", "DateTime", StoryStartFieldName, "<Today />"));
            //caml.RootNode = root;

            //caml.OrderByNodes.Add(new CAMLFieldRefNode(DisplayOrderFieldName, true));

            //var query = new SPQuery { Query = caml.GetCaml(), RowLimit = 5, };
            var stories = new FeaturedStories();

            SPListItemCollection items = list.Items; //GetItems(query);
            stories.AddRange(from SPListItem item in items
                             select new FeaturedStory
                                        {
                                            //changed it from a variable to use the data in the item itself.
                                            DisplayOrder = item.GetFormattedValue(DisplayOrderFieldName),
                                            Position = Int32.Parse(item.GetFormattedValue(DisplayOrderFieldName)),
                                            Title = item.Title,
                                            ImageUrl = item.GetFormattedValue(ImageFieldName),
                                            StoryLink = item.GetFormattedValue(StoryLinkFieldName), 
                                            // Unsupported fields
                                            SubTitle = "", ThumbHoverUrl = "", ThumbUrl = ""
                                        });


            stories.Sort(new StoryComparer());
            return stories;
        }

        #endregion Methods
    }
}
